package org.study.hadoop.md.ch3;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.study.hadoop.md.util.MRDPUtils;

import java.io.IOException;
import java.util.Map;

/**
 * 去重：给定一个用户评论的列表，得到去重的用户ID集
 */
public class DistinctUserDriver extends Configured implements Tool {

    public static class DistinctUserReducer extends Reducer<Text, NullWritable, Text, NullWritable> {
        @Override
        protected void reduce(Text key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {
            context.write(key, NullWritable.get());
        }
    }

    public static class DistinctUserMapper extends Mapper<Object, Text, Text, NullWritable> {
        private Text outUserId = new Text();

        @Override
        protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            Map<String, String> parsed = MRDPUtils.transformXmlToMap(value.toString());
            String userId = parsed.get("UserId");
            if (userId == null) {
                return;
            }
            outUserId.set(userId);
            context.write(outUserId, NullWritable.get());
        }
    }

    @Override
    public int run(String[] args) throws Exception {
        Path outPath = new Path("out");
        Path inPath = new Path("comment.txt");
        FileSystem fs = outPath.getFileSystem(getConf());
        if (fs.exists(outPath)) {
            fs.delete(outPath, true);
        }
        Job job = Job.getInstance(getConf(), "StackOverflow Distinct Users");
        job.setJarByClass(DistinctUserDriver.class);
        job.setMapperClass(DistinctUserMapper.class);
        job.setCombinerClass(DistinctUserReducer.class);
        job.setReducerClass(DistinctUserReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);
        FileInputFormat.addInputPath(job, inPath);
        FileOutputFormat.setOutputPath(job, outPath);
        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static void main(String[] args) throws Exception {
        int res = ToolRunner.run(new Configuration(), new DistinctUserDriver(), args);
        System.exit(res);
    }
}
